import dbx;
import webx;
import stdx;
import json;
import pdfkit;
import imgkit;


def main(app):
	tps = ('pdf', 'jpg', 'png');
	res = {'code': stdx.XG_FAIL};
	url = app.getParameter('url');
	type = app.getParameter('type').lower();
	code = app.getParameter('code').lower();
	if type not in tps: res['code'] = stdx.XG_PARAMERR;
	elif not stdx.CheckLength(code, (4, 5)): res['code'] = stdx.XG_PARAMERR;
	elif not stdx.CheckLength(url, (1, 1024)): res['code'] = stdx.XG_PARAMERR;
	else:
		chkcode = app.checkSession(('DOC_CHECKCODE'));
		if isinstance(chkcode, int): res['code'] = chkcode;
		elif code == chkcode[0]:
			app.setSession('DOC_CHECKCODE', '');
			name = app.getSequence() + '.' + type;
			path = 'dat/pub/' + name;
			res['code'] = stdx.XG_OK;
			res['link'] = '/' + path;
			res['name'] = name;
			try:
				pack = imgkit;
				if type == tps[0]: pack = pdfkit;
				pack.from_url(url, app.getPath() + path);
				app.trace('INF', 'save pdf[%s] from url[%s] success' % (path, url));
			except BaseException as e:
				app.trace('ERR', 'save pdf from url[%s] failed[%s]' % (url, str(e)));
		else: res['code'] = stdx.XG_AUTHFAIL
	return stdx.json(res);
